<template>
  <div class="image-upload">
    <el-upload
      :on-preview="preview"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :http-request="upload"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :limit="1"
      :class="{ disabled: isDisabled }"
      list-type="picture-card"
      action="#"
    >
      <i v-if="percent === 0" class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="showDialog" width="500px" top="8vh">
      <img width="100%" :src="imgUrl" alt="" />
      <div slot="title" class="title">图片预览</div>
    </el-dialog>
    <!-- 进度条组件 -->
    <div v-if="showProgress">
      <div>上传进度：<el-progress style="width: 180px;" :percentage="percent" /></div>
    </div>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDKOL3W2jvwjFUTHdDfGvuf5cYv1YpLWx9', // 身份识别ID
  SecretKey: '3qLhoeDVYLtKn57sfE9nBIQJuFoZ5JG6', // 身份秘钥
})

export default {
  name: 'ImageUpload',
  data() {
    return {
      fileList: [
        // {
        //   url:
        //     'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
        // },
      ],
      imgUrl: '',
      showDialog: false,
      percent: 0, // 进度条
      showProgress: false, // 控制展示进度条组件的布尔值
    }
  },
  computed: {
    // 是否显示上传框
    isDisabled() {
      return this.fileList.length >= 1
    },

    // 文件上传是否全部完成
    uploadAllSuccess() {
      return this.fileList.every(item => item.status === 'success')
    },
  },
  methods: {
    // 一、图片预览时触发
    preview(file) {
      this.imgUrl = file.url
      this.showDialog = true
    },

    // 二、图片移除时触发
    handleRemove(file) {
      // console.log(file)
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },

    // 三、点击+号上传时触发
    upload(params) {
      // console.log(params.file)
      // 执行上传到腾讯云操作
      if (params.file) {
        // 执行上传操作
        cos.putObject(
          {
            Bucket: 'violet-1305247684' /* 存储桶 */,
            Region: 'ap-shanghai' /* 存储桶所在地域，必须字段 */,
            Key: params.file.name /* 文件名 */,
            StorageClass: 'STANDARD', // 上传模式, 标准模式
            Body: params.file, // 上传文件对象
            // 上传过程中实时触发onProgress,可做进度条展示
            onProgress: progressData => {
              this.showProgress = true
              // console.log(JSON.stringify(progressData))
              // console.log(progressData)
              this.percent = parseInt(progressData.percent * 100)
            },
          },
          (err, data) => {
            // 上传成功以及失败的处理
            if (err) return console.log(err)
            // console.log(data)
            if (data.statusCode === 200) {
              // 找到对应的图片,修改状态以及路径
              const fileObj = this.fileList.find(item => item.uid === params.file.uid)
              // console.log(fileObj)
              fileObj.status = 'success'
              fileObj.url = 'https://' + data.Location
            }
            setTimeout(() => {
              this.showProgress = false
            }, 500)
          }
        )
      }
    },

    // 四、文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    handleChange(file, fileList) {
      // console.log(file)
      // co nsole.log(fileList)
      this.fileList = [...fileList]
    },

    // 五、配置上传前的校验, 只要通过校验, 才能进行上传
    beforeUpload(file) {
      // 1. 限制文件类型 file.type
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传的图片格式, 必须是jepg,jpg, gif, bmp, png的格式!')
        return false
      }
      // 2. 限制文件大小 file.size
      if (file.size / 1024 / 1024 >= 5) {
        this.$message.error('上传头像过大, 超过了5M, 必须5M以内')
        return false
      }
      return true
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep {
  .el-dialog__header {
    .el-icon-close:before {
      position: relative;
      top: 12px;
    }
    .title {
      color: white;
      font-size: 18px;
    }
  }
  .disabled {
    .el-upload--picture-card {
      display: none;
    }
  }
}
.el-progress {
  display: inline-block;
}
</style>
